package com.bigger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bigger.constant.ErrorConstant;
import com.bigger.constant.PasswordConstant;
import com.bigger.context.BaseContext;
import com.bigger.dto.EmployeePageDTO;
import com.bigger.dto.UpdateEmplDTO;
import com.bigger.entity.Employee;
import com.bigger.entity.Order;
import com.bigger.exception.BaseException;
import com.bigger.mapper.EmployeeMapper;
import com.bigger.result.PageResult;
import com.bigger.service.EmployeeService;
import com.bigger.vo.WagesVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.UUID;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public PageResult<Employee> page(EmployeePageDTO employeePageDTO) {
        Page<Employee> page=new Page<>(employeePageDTO.getPage(),employeePageDTO.getPageSize());

        QueryWrapper<Employee> wrapper=new QueryWrapper<Employee>()
                .like(
                        employeePageDTO.getName()!=null && !employeePageDTO.getName().isEmpty(),
                        "name",employeePageDTO.getName()
                )//模糊匹配(参数1：条件，参数2：表字段名，参数3：值)
                .eq(employeePageDTO.getSex()!=null,"sex",employeePageDTO.getSex())//精确查询
                ;
        Page<Employee> employeePage = employeeMapper.selectPage(page, wrapper);
        if (employeePage.getRecords().isEmpty()){ //这里的判断可以防止在其他页搜索时导致出现空数据的问题
            page=new Page<>(1,employeePageDTO.getPageSize());
            employeePage = employeeMapper.selectPage(page, wrapper);
        }
        List<Employee> records = employeePage.getRecords();
        PageResult<Employee> pageResult=new PageResult<>(employeePage.getTotal(),records);
        return pageResult;
    }

    @Override
    public void addEmpl(UpdateEmplDTO updateEmplDTO) {
        check(updateEmplDTO);//校验
        Employee employee=new Employee();
        BeanUtils.copyProperties(updateEmplDTO,employee);
        LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        //对一些未赋值的字段进行赋值
        employee.setId(null);
        employee.setUsername(getRandomUsername());
        employee.setPassword(PasswordConstant.DEFAULT_PASSWORD);
        employee.setCreateTime(now);
        employee.setUpdateTime(now);
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.insert(employee);
    }

    @Override
    public void updateEmpl(UpdateEmplDTO updateEmplDTO) {
        check(updateEmplDTO);//校验
        Employee employee=new Employee();
        BeanUtils.copyProperties(updateEmplDTO,employee);
        employee.setUpdateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateById(employee);
    }

    @Override
    public void deleteEmpl(Long id) {
        employeeMapper.deleteById(id);
    }

    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        return employee;
    }

    @Override
    public List<WagesVO> wages() {
        LocalDate now = LocalDate.now(ZoneId.of("Asia/Shanghai"));
        LocalDateTime start=LocalDateTime.of(
                now.with(TemporalAdjusters.firstDayOfMonth()) //获取当月的月初日期
                , LocalTime.MIN
        );
        LocalDateTime end=LocalDateTime.of(
                now.with(TemporalAdjusters.lastDayOfMonth()) //获取当月的月末日期
                , LocalTime.MAX
        );
        List<WagesVO> wages = employeeMapper.wages(start, end, Order.FINISH);//只查询完成订单
        if (wages.isEmpty()){ //为查询到直接返回空数组，防止下面取值报错
            return wages;
        }
        for (WagesVO wage : wages) {
            Double totalWages = wage.getTotalWages();
            BigDecimal decimal=new BigDecimal(totalWages);//金额计算必须使用此类计算（直接使用+-*/计算会出现误差）
            decimal= decimal.multiply(new BigDecimal("0.7"));//对工资进行3 7分发
            wage.setTotalWages(decimal.doubleValue());
        }
        return wages;
    }
    public void check(UpdateEmplDTO updateEmplDTO){
        if (StringUtils.isBlank(updateEmplDTO.getName())){
            throw new BaseException(ErrorConstant.EMPL_NAME_EMPTY);
        }
        if (!updateEmplDTO.getPhone().matches("1[3-9]\\d{9}")){
            throw new BaseException(ErrorConstant.EMPL_PHONE_ERROR);
        }
        if(updateEmplDTO.getSex()!=null&&updateEmplDTO.getSex()!=1&&updateEmplDTO.getSex()!=2){
            throw new BaseException(ErrorConstant.EMPL_SEX_ERROR);
        }
        if (updateEmplDTO.getJob()!=null&&updateEmplDTO.getJob()<1){
            throw new BaseException(ErrorConstant.EMPL_JOB_ERROR);
        }
    }
    /**
     * 获取随机用户名
     * @return
     */
    public String getRandomUsername(){
        String uuid= UUID.randomUUID()+"";
        int i = uuid.lastIndexOf("-");
        uuid=uuid.substring(i+1);
        return uuid;
    }
}
